<?php
error_reporting(E_ALL ^ E_NOTICE);
date_default_timezone_set("PRC"); //timezone

set_time_limit(0);
$con = mysql_connect("192.168.0.17","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("faithwar", $con);

$dateTime = date("Y-m-d",strtotime("-1 day"));
#$dateTime = date("Y-m-d");

    $deviceid_query = mysql_query("select DISTINCT deviceid from  tbheartbeat_last_temp"); //deviceid

while($deviceid = mysql_fetch_array($deviceid_query))
{
	 $TcRechargeNum_query = mysql_query("SELECT sum( `crystal` )
		FROM `temp`
		WHERE `deviceid` = '$deviceid[deviceid]'
		AND `crystal` >0"); //充值
     $TcRechargeNum = mysql_fetch_array($TcRechargeNum_query);
	 $TcUsedNum_query = mysql_query("SELECT sum( abs( crystal ) )
		FROM `temp`
		WHERE `deviceid` = '$deviceid[deviceid]'
		AND `crystal` <0"); //消费
     $TcUsedNum = mysql_fetch_array($TcUsedNum_query);

  $sql = "UPDATE  tbheartbeat_last_temp SET TcRechargeNum= '$TcRechargeNum[0]',TcUsedNum= '$TcUsedNum[0]' WHERE deviceid= '$deviceid[deviceid]'";  //update tbheartbeat_last_temp TcRechargeNum and TcUsedNum
   if(mysql_query($sql,$con)){
    echo "1 update is ok!";
} else {
    echo "failed".mysql_error();
}

}


  $sql2 = "UPDATE  tbheartbeat_last_temp SET TcRechargeNum= 0 WHERE TcRechargeNum = ''";  //update tbheartbeat_last_temp if TcRechargeNum and TcUsedNum =0
  $sql3 = "UPDATE  tbheartbeat_last_temp SET TcUsedNum= 0 WHERE TcUsedNum =''";  //update tbheartbeat_last_temp if TcRechargeNum and TcUsedNum =0
 
   if(mysql_query($sql2,$con)){
    echo "2 update is ok!";
} else {
    echo "failed".mysql_error();
}
  if(mysql_query($sql3,$con)){
    echo "3 update is ok!";
} else {
    echo "failed".mysql_error();
}

mysql_close($con);
?>